package com.yl.module.property.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yl.common.constant.Constants;
import com.yl.common.core.domain.entity.SysUser;
import com.yl.common.exception.ServiceException;
import com.yl.common.utils.NumberUtils;
import com.yl.framework.interceptor.UserContext;
import com.yl.module.file.domain.FileType;
import com.yl.module.file.domain.vo.File2VO;
import com.yl.module.file.service.FileService;
import com.yl.module.property.domain.Property;
import com.yl.module.property.domain.PropertyType;
import com.yl.module.property.domain.dto.PropertyAddOrUpdDTO;
import com.yl.module.property.domain.dto.PropertyMaintainAddOrUpdDTO;
import com.yl.module.property.mapper.PropertyMaintainMapper;
import com.yl.module.property.service.PropertyMaintainService;
import com.yl.module.property.service.PropertyService;
import com.yl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.yl.module.property.domain.vo.PropertyMaintainVO;
import com.yl.module.property.domain.dto.PropertyMaintainDTO;
import com.yl.module.property.domain.PropertyMaintain;
import cn.hutool.core.bean.BeanUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 资产保养记录表 Service实现类
 * @author makejava
 * @date 2024-10-23 15:54:15
 */
@Service
@Slf4j
public class PropertyMaintainServiceImpl extends ServiceImpl<PropertyMaintainMapper, PropertyMaintain> implements PropertyMaintainService {

	@Autowired
	PropertyMaintainMapper propertyMaintainMapper;
	@Autowired
	FileService fileService;
	@Autowired
	ISysUserService sysUserService;
	@Autowired
	PropertyService propertyService;

   /**
	 * 查询所有
	 */
	@Override
	public List<PropertyMaintainVO> getAll(){
		List<PropertyMaintain> list = this.list();
		List<PropertyMaintainVO> result = BeanUtil.copyToList(list, PropertyMaintainVO.class);
		return result;
	}

	/**
     * 分页查询
     */
	@Override
    public Page<PropertyMaintain> getPage(PropertyMaintainDTO dto){
		//创建分页对象
		Page<PropertyMaintain> page = new Page(dto.getPageNum(), dto.getPageSize());
		//dto查询条件转分页条件
		LambdaQueryWrapper<PropertyMaintain> lqw = new LambdaQueryWrapper<>();
		Page<PropertyMaintain> result = propertyMaintainMapper.selectPage(page, lqw);
		return result;
	}

	@Override
	public List<PropertyMaintainVO> getByPropertyId(Integer propertyId){
		LambdaQueryWrapper<PropertyMaintain> lqw = new LambdaQueryWrapper<>();
		lqw.eq(PropertyMaintain::getPropertyId,propertyId);
		lqw.eq(PropertyMaintain::getDeleteFlag, Constants.NO);
		List<PropertyMaintain> list = this.list(lqw);
		if(CollUtil.isEmpty(list)){
			return new ArrayList<>();
		}
		List<PropertyMaintainVO> result = BeanUtil.copyToList(list, PropertyMaintainVO.class);

		List<Long> ids = result.stream()
				.map(i -> i.getId())
				.collect(Collectors.toList());
		Map<Long, List<File2VO>> fileMap = fileService.getMap(FileType.TypeEnum.FILE_TYPE_1001.getCode(), ids);

		List<Long> userIds = result.stream()
				.filter(i -> !NumberUtils.longEmpty(i.getUserId()))
				.map(i -> i.getUserId())
				.collect(Collectors.toList());
		Map<Long, SysUser> userMap = sysUserService.getMapByIds(userIds);

		for(PropertyMaintainVO i:result){
			if(fileMap.containsKey(i.getId())){
				i.setFiles(fileMap.get(i.getId()));
			}
			i.setUserName(sysUserService.getNameByMap(userMap,i.getUserId()));
		}
        return result;
    }

	/**
	 * 添加
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long add(PropertyMaintainAddOrUpdDTO dto){

		//判断是否闲置
		Property property = propertyService.getById(dto.getPropertyId());
		if(Constants.YES.equals(property.getIsIdle())){
			throw new ServiceException("该资产已闲置，无法添加保养记录");
		}

		//计算下次保养时间
		nextTimeMaintain(dto,property);

		//添加保养记录
		PropertyMaintain propertyMaintain = BeanUtil.copyProperties(dto, PropertyMaintain.class);
		propertyMaintain.setUserId(UserContext.getUser().getUserId());
		if(!dto.getPropertyTypeId().equals(PropertyType.IdEnum.ID_4.getCode())){
			//非构件分类保养 没有分类id
			propertyMaintain.setPropertyTypeIdMaintain(null);
		}
		this.save(propertyMaintain);

		if(!CollectionUtils.isEmpty(dto.getFileIds())){
			fileService.addSave(propertyMaintain.getId(),dto.getFileIds());
		}

		return propertyMaintain.getId();
	}

	/**
	 * 计算下次保养时间
	 */
	public void nextTimeMaintain(PropertyMaintainAddOrUpdDTO dto,Property property){
		//获取下次保养时间
		LocalDateTime nextTimeMaintain = dto.getMaintainTime().plusMonths(property.getMaintainPeriod());

		//非构件计算下次保养时间
		if(!dto.getPropertyId().equals(PropertyType.IdEnum.ID_4.getCode())){
			Property propertyUpd = new Property();
			propertyUpd.setId(dto.getPropertyId());
			propertyUpd.setNextTimeMaintain(nextTimeMaintain);
			propertyUpd.setUpdateTime(LocalDateTime.now());
			propertyService.updateById(propertyUpd);
			return;
		}

		//构件计算下次保养时间
		Property propertyUpd = new Property();
		propertyUpd.setNextTimeMaintain(nextTimeMaintain);
		propertyUpd.setUpdateTime(LocalDateTime.now());
		//修改条件
		LambdaUpdateWrapper<Property> luw = new LambdaUpdateWrapper<>();
		luw.eq(Property::getPropertyTypeId3, dto.getPropertyTypeIdMaintain());
		luw.eq(Property::getUpdateTime, LocalDateTime.now());
		//开始修改
		propertyService.update(propertyUpd, luw);
	}

	/**
	 * 通过主键修改
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void upd(PropertyMaintainAddOrUpdDTO dto){
		PropertyMaintain propertyMaintain = BeanUtil.copyProperties(dto, PropertyMaintain.class);
		propertyMaintain.setUserId(UserContext.getUser().getUserId());
		if(!dto.getPropertyTypeId().equals(PropertyType.IdEnum.ID_4.getCode())){
			//非构件分类保养 没有分类id
			propertyMaintain.setPropertyTypeIdMaintain(null);
		}
	    this.updateById(propertyMaintain);
		//修改保养件记录 已同产品确认 不需要再去重新计算保养日期

		fileService.updSave(FileType.TypeEnum.FILE_TYPE_1001.getCode(),propertyMaintain.getId(),dto.getFileIds());
	}

	@Override
	public void del(Long id){
		if(NumberUtils.longEmpty(id)){
			throw new ServiceException("参数id不能为空");
		}

		PropertyMaintain propertyMaintain = new PropertyMaintain();
		propertyMaintain.setId(id);
		propertyMaintain.setDeleteFlag(Constants.YES);
		this.updateById(propertyMaintain);
	}

}



